import { captureError } from './rrweb';
import ErrorStackParser from 'error-stack-parser';

export function initErrorHandling(app) {
  // Vue错误捕获
  app.config.errorHandler = (err, vm, info) => {
    const errorStack = ErrorStackParser.parse(err);

    captureError({
      type: 'VUE_ERROR',
      reason: errorStack[0],
      timestamp: Date.now(),
    });
  };

  // 全局错误捕获
  window.addEventListener('error', (event) => {
    captureError({
      type: 'WINDOW_ERROR',
      message: event.message,
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      timestamp: Date.now(),
    });
  });

  // 未处理的Promise拒绝
  window.addEventListener('unhandledrejection', (event) => {
    captureError({
      type: 'PROMISE_REJECTION',
      reason: event.reason?.stack || event.reason,
      timestamp: Date.now(),
    });
  });
}
